package com.longjianghuasheng.logistics.business.grab_an_order

import android.os.Bundle
import com.longjianghuasheng.logistics.R
import com.longjianghuasheng.logistics.base.BaseTitleFragment
import com.longjianghuasheng.logistics.databinding.FragmentGrabAnOrderListBinding
import com.longjianghuasheng.logistics.eventViewModel
import com.longjianghuasheng.logistics.ext.initLinerDecoration
import com.longjianghuasheng.logistics.ext.observer

class GrabAnOrderListFragment :
    BaseTitleFragment<GrabAnOrderViewModel, FragmentGrabAnOrderListBinding>() {
    override fun isRefresh(): Boolean = true
    override fun isLoadMore(): Boolean = true
    private val grabAnOrderAdapter by lazy {

        GrabAnOrderAdapter()
    }

    override fun layoutId(): Int = R.layout.fragment_grab_an_order_list

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        initTitleBar("抢单大厅", true)
        grabAnOrderAdapter.run {

            mDatabind.recyclerView.initLinerDecoration(adapter = this)

            setOnItemClickListener { adapter, view, position ->

                navigate(R.id.grabASingleDetailsFragment, Bundle().apply {
                    putInt("id", data[position].id ?: 0)
                })

            }

            addChildClickViewIds(R.id.btn_orders)

            setOnItemChildClickListener { adapter, view, position ->
                when (view.id) {
                    R.id.btn_orders -> {
                        mViewModel.id = data[position].id ?: 0
                        mViewModel.driver_do()

                    }
                    else -> {}
                }

            }

        }


    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.result.observer(this) {
            if (mViewModel.page == 1) {
                if (it.isNullOrEmpty()) {
                    mStatefulLayout.showEmpty()
                    return@observer
                }
                grabAnOrderAdapter.setNewInstance(it)
            } else {

                if (it.isNullOrEmpty()) {
                    mViewModel.page--
                    smartLayout.setNoMoreData(true)
                    return@observer
                }

                grabAnOrderAdapter.addData(it)
            }

        }
        mViewModel.notify.observer(this) {

            grabAnOrderAdapter.removeAt(grabAnOrderAdapter.data.indexOfFirst { it.id == mViewModel.id })

        }
        eventViewModel.onGrabASingleUpdateEvent.observeInFragment(this) { id ->
            grabAnOrderAdapter.removeAt(grabAnOrderAdapter.data.indexOfFirst { it.id == id })

        }

    }

    override fun initData() {
        super.initData()
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        mViewModel.requestData()
    }

}